package com.hyg.module_report.ui.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hyg.lib_base.Net.NetworkUtils;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.DataModel.ReceiveData;
import com.hyg.lib_common.DataModel.report.ReportListDetailData;
import com.hyg.lib_common.DataModel.report.V2ReportListDetailData;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.lib_common.constant.Constants;
import com.hyg.module_report.R;
import com.hyg.module_report.adapter.ReportListAdapter;
import com.hyg.module_report.model.ReportListData;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.angmarch.views.NiceSpinner;

import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import okhttp3.FormBody;

/**
 * 报告列表页面
 */

@Route(path = Constants.PATH_ACTIVITY_MODULE_REPORTS_ALLLIST)
public class ReportListScreenActivity extends BaseActivity {
    private RecyclerView RV_Report;
    private ReportListAdapter reportListAdapter;
    private ArrayList<ReportListData> reportListData = new ArrayList<ReportListData>();
    private ArrayList<ReportListData> reportListDatas = new ArrayList<ReportListData>();
    private NiceSpinner all_sort, all_hospital, all_time;
    private List<String> timeData = new LinkedList<>(Arrays.asList("全部时间", "近一周", "近30天", "近半年", "近一年"));
    private List<String> hospitalData = new LinkedList<>(Arrays.asList("全部机构", "慧医谷中医院", "慧医谷中西医院"));
    private List<String> sortData = new LinkedList<>(Arrays.asList("默认排序", "时间由近到远", "时间由远到近"));
    private ImageView back, add, iv_zanwubaogao;
    private Button bt_tianjiabaogao;
    private RefreshLayout refreshLayout;
    private MyHandler myHandler;

    private boolean v1_isFinish = false;
    private boolean v2_isFinish = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reports_list);
        init();
    }

    @Override
    public void onResume() {
        super.onResume();
        // 是否需要刷新数据
        if (null != sn.getString("InsertReport", "") && sn.getString("InsertReport", "").equals("1")) {
            editorn = sn.edit();
            editorn.putString("InsertReport", "0");
            editorn.commit();
            getListData();
        }
    }


    public void init() {
        initData();
        initView();
    }

    /**
     * description: 初始化数据
     *
     * @author visitant
     * @time 2020/12/9 14:33
     */
    public void initData() {
        sn = this.getSharedPreferences("HYG", Context.MODE_PRIVATE);
        myHandler = new MyHandler(this);
        getPermissions(needPermissions, null);
        getListData();
    }

    /**
     * description: 初始化页面显示
     *
     * @author visitant
     * @time 2020/12/9 14:33
     */
    public void initView() {
        StatusBarUtil.setStatusBar(1, this, getResources().getColor(R.color.white), 00, null, null, true);
        getWindow().setBackgroundDrawable(getResources().getDrawable(com.hyg.lib_common.R.drawable.window_white));
        initButton();
        initReportList();
        initRefreshLayout();
        initSpinner();
    }

    public void getListData() {
        reportListDatas.clear();
        reportListData.clear();
        hospitalData.clear();
        hospitalData.add("全部机构");                   //机构目录
        GetReportListAddr();
        GetV2ReportListAddr();
    }

    /**
     * description: 初始化页面按钮  返回  添加
     *
     * @author visitant
     * @time 2020/12/9 14:28
     */
    public void initButton() {
        back = findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {                        //返回按钮
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                finish();
                overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
            }
        });

        add = (ImageView) findViewById(R.id.add);                                   //右上添加报告
        add.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                Intent it = new Intent(ReportListScreenActivity.this, InsertReportActivity.class);
                startActivity(it);
                overridePendingTransition(R.anim.fade, R.anim.hold);
            }
        });
        iv_zanwubaogao = (ImageView) findViewById(R.id.iv_zanwubaogao);

        bt_tianjiabaogao = (Button) findViewById(R.id.bt_tianjiabaogao);            //中间添加报告
        bt_tianjiabaogao.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                Intent it = new Intent(ReportListScreenActivity.this, InsertReportActivity.class);
                startActivity(it);
                overridePendingTransition(R.anim.fade, R.anim.hold);
            }
        });
    }

    /**
     * description: 初始化列表排序头部
     *
     * @author visitant
     * @time 2020/12/9 14:26
     */
    public void initSpinner() {
        all_time = (NiceSpinner) findViewById(R.id.all_time);
        all_hospital = (NiceSpinner) findViewById(R.id.all_hospital);
        all_sort = (NiceSpinner) findViewById(R.id.all_sort);
        all_time.attachDataSource(timeData);
        all_hospital.attachDataSource(hospitalData);
        all_sort.attachDataSource(sortData);
        all_time.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {     //spinner全部时间
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                setReportListAdapter(timeData.get(position),
                        hospitalData.get(all_hospital.getSelectedIndex()),
                        sortData.get(all_sort.getSelectedIndex()));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        all_hospital.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {       //spinner机构
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                setReportListAdapter(timeData.get(all_time.getSelectedIndex()),
                        hospitalData.get(position),
                        sortData.get(all_sort.getSelectedIndex()));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        all_sort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {           //spinner默认排序
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                setReportListAdapter(timeData.get(all_time.getSelectedIndex()),
                        hospitalData.get(all_hospital.getSelectedIndex()),
                        sortData.get(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        setReportListAdapter(timeData.get(0), hospitalData.get(0), sortData.get(0));
    }

    /**
     * description: 初始化报告列表
     *
     * @author visitant
     * @time 2020/12/9 14:26
     */
    public void initReportList() {
        RV_Report = findViewById(R.id.RV_Report);                                         //详细列表
        RV_Report.setNestedScrollingEnabled(false);
        RV_Report.setLayoutManager(new GridLayoutManager(this, 1));
        RV_Report.setItemAnimator(new DefaultItemAnimator());
        RV_Report.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));//RV的item分割线
        reportListAdapter = new ReportListAdapter(ReportListScreenActivity.this, reportListDatas);
        RV_Report.setAdapter(reportListAdapter);
        reportListAdapter.setOnItemClickLitener(new ReportListAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent it;
                String version = reportListDatas.get(position).getVersion();
                if (version.equalsIgnoreCase("1.0")) {
                    it = new Intent(ReportListScreenActivity.this, HealthReportActivity.class);
                } else {
                    it = new Intent(ReportListScreenActivity.this, HealthReportV2Activity.class);
                }
                if (reportListDatas.size() != 0 && reportListDatas.size() > position) {
                    it.putExtra("MedicalId", reportListDatas.get(position));
                    startActivity(it);
                } else {
                    new AlertDialog.Builder(ReportListScreenActivity.this)
                            .setMessage("当前活动无实体内容，敬请期待")
                            .setPositiveButton("我知道了！", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int arg1) {
                                    if (Utils.isFastClick()) {
                                        return;
                                    }
                                }
                            }).show();
                }
            }

            public void onItemLongClick(View view, int position) {
            }
        });

    }


    /**
     * description:  初始化下拉view
     *
     * @author visitant
     * @time 2020/12/9 14:25
     */
    public void initRefreshLayout() {
        refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);               //下拉刷新
        refreshLayout.setDragRate(0.5f);//显示下拉高度/手指真实下拉高度=阻尼效果
        refreshLayout.setReboundDuration(300);//回弹动画时长（毫秒）
        refreshLayout.setHeaderHeight(40);//Header标准高度（显示下拉高度>=标准高度 触发刷新）
        refreshLayout.setHeaderMaxDragRate(2);//最大显示下拉高度/Header标准高度
        refreshLayout.setHeaderTriggerRate(1);//触发刷新距离 与 HeaderHeight 的比率1.0.4
        refreshLayout.setFooterTriggerRate(0.5f);//触发加载距离 与 FooterHeight 的比率1.0.4

        refreshLayout.setEnableRefresh(true);//是否启用下拉刷新功能f
        refreshLayout.setEnableLoadMore(false);//是否启用上拉加载功能
        refreshLayout.setEnableOverScrollBounce(true);//是否启用越界回弹
        refreshLayout.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
        refreshLayout.setEnableHeaderTranslationContent(true);//是否下拉Header的时候向下平移列表或者内容
        refreshLayout.setEnableLoadMoreWhenContentNotFull(true);//是否在列表不满一页时候开启上拉加载功能
        refreshLayout.setDisableContentWhenRefresh(false);//是否在刷新的时候禁止列表的操作
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                /*    下拉刷新      */
                //                mIsRefreshing = true;
                getListData();
                refreshlayout.finishRefresh(1500/*,false*/);//传入false表示刷新失败
            }
        });
    }


    /**
     * description: 获取报告列表数据
     *
     * @author visitant
     * @time 2020/12/9 14:40
     */
    public void GetReportListAddr() {
        Log.i("lgb", "GetReportListAddr:token==== "+sn.getString("token", ""));
        if (UINetWork(NetworkUtils.isConnected(this)))//检查网络是否断开的 提示，决定是否访问服务器
        {
            v1_isFinish = false;
            String str_tag = "1";
            FormBody formBody = new FormBody.Builder()
                    .add("token", sn.getString("token", ""))//设置参数名称和参数值
                    .build();
            sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getReportListAddr);
        } else {
            v1_isFinish = true;
        }
    }


    /**
     * description: 获取v2报告列表数据
     *
     * @author visitant
     * @time 2020/12/9 14:40
     */
    public void GetV2ReportListAddr() {
        if (UINetWork(NetworkUtils.isConnected(this)))//检查网络是否断开的 提示，决定是否访问服务器
        {
            v2_isFinish = false;
            String str_tag = "2";
            FormBody formBody = new FormBody.Builder()
                    .add("token", sn.getString("token", ""))//设置参数名称和参数值
                    .build();
            sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getV2ReportListAddr);
        } else {
            v2_isFinish = true;
        }
    }


    /**
     * description:列表排序
     *
     * @author visitant
     * @time 2020/12/9 14:41
     */
    //开线程完成筛选排序工作,并更新，不开线程的原因为 大部分手机，开线程后，延迟了，但不显示，第二次进入才自动显示（原因暂时未知，需要理解RXAndroid的原理）。
    public void setReportListAdapter(final String time, final String hospital, final String sort) {
        reportListDatas.clear();
        for (ReportListData item : reportListData) {
            if (time.equals("全部时间") && hospital.equals("全部机构")) {
                reportListDatas.add(item);
            } else if (!time.equals("全部时间") && hospital.equals("全部机构")) {
                if (compareDate(item.getReport_date()).contains(time)) {
                    reportListDatas.add(item);
                }
            } else if (time.equals("全部时间") && !hospital.equals("全部机构")) {
                if (hospital.equals(item.getReport_hospital())) {
                    reportListDatas.add(item);
                }
            } else if (!time.equals("全部时间") && !hospital.equals("全部机构")) {
                if (compareDate(item.getReport_date()).contains(time) && hospital.equals(item.getReport_hospital())) {
                    reportListDatas.add(item);
                }
            }
            if (!sort.equals("默认排序")) {
                sortBefore before = new sortBefore();
                sortAfter after = new sortAfter();
                if (sort.equals("时间由近到远")) {
                    Collections.sort(reportListDatas, before);
                } else if (sort.equals("时间由远到近")) {
                    Collections.sort(reportListDatas, after);
                }
            }
        }
        reportListAdapter.notifyDataSetChanged();
    }


    //比较与当天时间相差天数，返回对应所属天数类型
    public String compareDate(String dates) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long timeMillis = System.currentTimeMillis();
        try {
            //            String what = dateToStamp(dates);
            String today = stampToDate(timeMillis);

            Date d1 = format.parse(today); //当前时间
            Date d2 = format.parse(dates); //之前记录的时间

            Long diff = d1.getTime() - d2.getTime(); //两时间差，精确到毫秒
            //以天数为单位取整
            Long day = diff / (1000 * 60 * 60 * 24);
            //以小时为单位取整
            Long hour = (diff / (60 * 60 * 1000) - day * 24);
            //以分钟为单位取整
            Long min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            //以秒为单位
            Long second = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);

            int result = 0;
            if (day <= 366)
                result++;
            if (day <= 183)
                result++;
            if (day <= 30)
                result++;
            if (day <= 7)
                result++;

            if (result == 4) {
                return "近一周|近30天|近半年|近一年";
            } else if (result == 3) {
                return "近30天|近半年|近一年";
            } else if (result == 2) {
                return "近半年|近一年";
            } else if (result == 1) {
                return "近一年";
            } else {
                return "全部时间";
            }

        } catch (ParseException e) {
            Log.d("MyDataBaseHelper 数据内的时间", "报告时间格式错误");
            //            Log.d(CrashTAG,""+e.getMessage());
            return "报告时间格式错误";
        }
    }

    /**
     * 将时间转换为时间戳
     */
    public String dateToStamp(String time) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(time);
        long ts = date.getTime();
        return String.valueOf(ts);
    }

    /**
     * 将时间戳转换为时间
     */
    public String stampToDate(long timeMillis) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(timeMillis);
        return simpleDateFormat.format(date);
    }


    public static Date stringToDate(String dateString) {
        //        ParsePosition position = new ParsePosition(0);
        if (null == dateString || dateString.equals("null") || dateString.equals("")) {
            Date date = new Date();
            return date;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //        Date dateValue = simpleDateFormat.parse(dateString, position);
        Date dateValue = null;
        try {
            dateValue = simpleDateFormat.parse(dateString);
        } catch (ParseException e) {
            Log.d(CrashTAG, "" + e.getMessage());
        }
        return dateValue;
    }

    //对列表根据日期排序
    public class sortBefore implements Comparator<ReportListData> {
        @Override
        public int compare(ReportListData lhs, ReportListData rhs) {
            Date d1 = stringToDate(lhs.getReport_date());
            Date d2 = stringToDate(rhs.getReport_date());
            // 对日期字段进行升序，如果欲降序可采用after方法
            if (d1.before(d2)) {
                return 1;
            } else if (d1.equals(d2)) {
                return 0;
            } else {
                return -1;
            }
        }
    }

    //对列表根据日期排序
    public class sortAfter implements Comparator<ReportListData> {
        @Override
        public int compare(ReportListData lhs, ReportListData rhs) {
            Date d1 = stringToDate(lhs.getReport_date());
            Date d2 = stringToDate(rhs.getReport_date());
            // 对日期字段进行升序，如果欲降序可采用after方法
            if (d1.after(d2)) {
                return 1;
            } else if (d1.equals(d2)) {
                return 0;
            } else {
                return -1;
            }
        }
    }

    @SuppressLint("NewApi")
    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.REQUEST_INSTALL_PACKAGES,
    };
    private static final int PERMISSON_REQUESTCODE = 0;
    /**
     * 判断是否需要检测，防止不停的弹框
     */
    private boolean isNeedCheck = true;

    private class MyHandler extends Handler {
        private final WeakReference<Context> reference;
        private ReportListScreenActivity activity;

        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (ReportListScreenActivity) reference.get();
        }

        public void handleMessage(Message msg) {
            ReceiveData receiveData = JSONObject.parseObject(msg.obj.toString(), ReceiveData.class);
            switch (msg.what) {
                case 1://用手机号和验证码登录
                    v1_isFinish = true;
                    if (receiveData.getCode().equals("200")) {
                        ArrayList<ReportListDetailData> listData=new ArrayList<>();
                        listData = (ArrayList<ReportListDetailData>) JSONArray.parseArray(receiveData.getData(), ReportListDetailData.class);
//                        Log.i("lgb", "handleMessage: "+listData.size());
                        if (listData != null) {
                            for (int i = 0; i < listData.size(); i++) {
                                ReportListData data = new ReportListData(listData.get(i).getId() + "", listData.get(i).getPatientName()
                                        , listData.get(i).getCreateTime(), listData.get(i).getDiagnosticMechanismName());
                                reportListDatas.add(data);
                                reportListData.add(data);
                                if (!hospitalData.contains(listData.get(i).getDiagnosticMechanismName())) {
                                    hospitalData.add(listData.get(i).getDiagnosticMechanismName());
                                }
                            }
                        }
                    }
                    else {
                        if(v2_isFinish){
                            activity.ErrorDialog(receiveData.getMessage());
                        }
                    }
                    hideView(activity.reportListAdapter);
                    break;
                case 2:
                    v2_isFinish = true;
                    if (receiveData.getCode().equals("200")) {
                        ArrayList<V2ReportListDetailData> listData = (ArrayList<V2ReportListDetailData>) JSONArray.parseArray(receiveData.getData(), V2ReportListDetailData.class);
                        Log.i("lgb", "handleMessage: "+listData.size());
                        if (listData != null) {
                            Log.i("lgb", "handleMessage:size= "+listData.size());
                            for (int i = 0; i < listData.size(); i++) {
                                ReportListData data = new ReportListData(listData.get(i).getId() + "", listData.get(i).getUserName()
                                        , listData.get(i).getCreateTime(), listData.get(i).getOrgName(), listData.get(i).getDataVersion(), listData.get(i));
                                reportListDatas.add(data);
                                reportListData.add(data);
                                if (!hospitalData.contains(listData.get(i).getOrgName())) {
                                    hospitalData.add(listData.get(i).getOrgName());
                                }
                            }
                        }
                    }else {
                        if(v1_isFinish)
                        activity.ErrorDialog(receiveData.getMessage());
                    }
                    hideView(activity.reportListAdapter);
                    break;
            }
        }
    }

    public void hideView(ReportListAdapter adapter) {
        if (reportListDatas.size() == 0) {
            iv_zanwubaogao.setVisibility(View.VISIBLE);
            bt_tianjiabaogao.setVisibility(View.VISIBLE);
            all_time.setVisibility(View.GONE);
            all_hospital.setVisibility(View.GONE);
            all_sort.setVisibility(View.GONE);
            RV_Report.setVisibility(View.GONE);
        } else {
            iv_zanwubaogao.setVisibility(View.GONE);
            bt_tianjiabaogao.setVisibility(View.GONE);
            all_time.setVisibility(View.VISIBLE);
            all_hospital.setVisibility(View.VISIBLE);
            all_sort.setVisibility(View.VISIBLE);
            RV_Report.setVisibility(View.VISIBLE);
//            adapter.notifyDataSetChanged();

            if (v1_isFinish && v2_isFinish) {
                Log.i("lgb", "hideView: "+timeData.get(all_time.getSelectedIndex()));
                Log.i("lgb", "hideView: "+hospitalData.get(all_hospital.getSelectedIndex()));
                Log.i("lgb", "hideView: "+sortData.get(all_sort.getSelectedIndex()));
                setReportListAdapter(timeData.get(all_time.getSelectedIndex()),
                        hospitalData.get(all_hospital.getSelectedIndex()),
                        sortData.get(all_sort.getSelectedIndex()));
            }
        }
    }


    protected void onStop() {
        super.onStop();
        if (this.isFinishing()) {
            myHandler.removeCallbacksAndMessages(null);
        }
    }

}